<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item">
         <el-option v-for="item in statusJson" :key="item.value" :label="item.label" :value="item.value"/>
       </el-select> 
      <el-button v-waves class="filter-item" type="success" icon="el-icon-edit" @click="addCoupon">
        添加
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
    </div>
    <el-table ref="table" v-loading="listLoading" :data="list" border fit highlight-current-row row-key="id" style="width: 100%;" :max-height="tableHeight">
      <el-table-column label="优惠券标题" prop="title" align="center" />
      <!-- <el-table-column label="限领张数" prop="limitCount" align="center" /> -->
      <el-table-column label="抵扣价格" prop="price" align="center" />
      <el-table-column label="使用金额门槛" prop="conditionPrice" align="center" />
      <!-- <el-table-column label="已领取数量" prop="takeCount" align="center" />
      <el-table-column label="已使用数量" prop="usedCount" align="center" /> -->
      <el-table-column label="有效天数" prop="validDays" align="center" />
      <el-table-column label="使用范围" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.useRangeType == 1">全品类</el-tag>
          <el-tag v-else-if="row.useRangeType == 2" type="success">部分商品可用</el-tag>
          <el-tag v-else type="warning">部分类别可用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="说明" prop="remark" align="center">
        <template slot-scope="{row}">
          <el-popover
            placement="bottom"
            title=""
            width="200"
            trigger="hover">
            <div style="white-space: pre-wrap;">{{ row.remark }}</div>
            <el-button type="mini" slot="reference">详情</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="发放开始时间" prop="startTime" align="center" />
      <el-table-column label="发放结束时间" prop="endTime" align="center" />
      <el-table-column label="状态" prop="status" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.status == 1" type="success">正常</el-tag>
          <el-tag v-else type="danger">下线</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" min-width="120">
        <template slot-scope="{row}">
          <el-button type="danger" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />
    
    <el-dialog title="新建" :visible.sync="dialogAddFormVisible" width="50%" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="135px">
        <el-form-item label="优惠券标题：" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="门槛金额：" prop="conditionPrice">
          <el-input type="number" placeholder="满多少才可以使用（为0则不限制金额）" v-model="temp.conditionPrice" />
        </el-form-item>
        <el-form-item label="抵扣价格：" prop="price">
          <el-input type="number" v-model="temp.price" />
        </el-form-item>
        <el-form-item label="领取起有效天数：" prop="validDays">
          <el-input type="number" v-model="temp.validDays" />
        </el-form-item>
        <el-form-item label="使用范围：" prop="useRangeType">
          <el-select v-model="temp.useRangeType " placeholder="使用范围" clearable class="filter-item">
         <el-option v-for="item in typeJson" :key="item.value" :label="item.label" :value="item.value"/>
       </el-select> 
        </el-form-item>
        <el-form-item label="时间：" prop="startDate">
          <DatePicker :startDate.sync="temp.startTime" :endDate.sync="temp.endTime" clearable />
        </el-form-item>
        <el-form-item label="说明：" prop="remark">
          <el-input type="textarea" v-model="temp.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { couponPageByQo, couponSave, couponRemove } from '@/api/zcyx'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import updateTableMixin from '@/mixin/updateTable'
import DatePicker from '@/components/DatePicker'
import {mapGetters} from "vuex";

export default {
  name: 'ZcyxCoupon',
  directives: { waves },
  props: {},
  components: {
    Pagination,
    DatePicker
  },
  mixins: [updateTableMixin],
  data() {
    const validateDate = (rule, value, callback) => {
      if (!this.temp.startTime || !this.temp.endTime) {
        callback(new Error('请选择时间'))
      } else if (new Date(this.temp.startTime).getTime() < new Date().getTime()) {
        callback(new Error('起始时间必须晚于当前时间'))
      } else if(this.temp.startTime == new Date().getTime()) {
				callback(new Error('起始时间不能等于当前时间'))
			} else {
        callback()
      }
    }

    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        type: 1,
        platform: 2,
        pageNo: 1,
        pageSize: 20,
        status: ''
      },
      dialogAddFormVisible: false,
      rules: {
        conditionPrice: [{ required: true, message: '请输入', trigger: 'blur' }],
        price: [{ required: true, message: '请输入', trigger: 'blur' }],
        startTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        endTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        validDays: [{ required: true, message: '请输入', trigger: 'blur' }],
        title: [{ required: true, message: '请输入', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入', trigger: 'blur' }],
        useRangeType : [{ required: true, message: '请输入', trigger: 'blur' }],
        startDate: [{validator: validateDate}],
      },
      temp: {
        conditionPrice: '',
        price: '',
        startTime: '',
        endTime: '',
        validDays: '',
        useRangeType: '',
        title: '',
        remark: ''
      },
      statusJson: [
        {
          value: '1',
          label: '正常'
        }, {
          value: '0',
          label: '下线'
        }
      ],
      typeJson: [
        {
          value: '1',
          label: '全品类'
        }, 
        {
          value: '2',
          label: '部分商品可用'
        }, 
        {
          value: '3',
          label: '部分类别可用'
        }
      ]
    }
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {
    $route: {
      handler: function(route) {
        const t = route.query.t;
        if (t) {
          this.handleFilter()
        }
      },
      immediate: true
    }
  },
  methods: {
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    getList() {
      this.listLoading = true
      if (this.userInfo.id == 49944) {
        this.listQuery.platform = 2
      } else {
        this.listQuery.platform = 3
      }
      couponPageByQo(this.listQuery).then(response => {
        this.list = response.list || []
        this.total = response.totalCount
        this.listLoading = false
        this.updateTableHeight()
      })
    },
    addCoupon() {
      // this.dialogAddFormVisible = true
      // this.temp = {
      //   conditionPrice: '',
      //   price: '',
      //   startTime: '',
      //   endTime: '',
      //   validDays: '',
      //   title: '',
      //   remark: ''
      // }

      this.$router.push({
        path: "/zcyx/zcyxCouponSave"
      });
    },
    saveData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let info = `<div>优惠券标题：${this.temp.title}</div>
    <div>门槛金额：${this.temp.conditionPrice}</div>
    <div>抵扣价格：${this.temp.price}</div>
    <div>领取起有效天数：${this.temp.validDays}</div>
    <div>时间：${this.temp.startTime} - ${this.temp.endTime}</div>
    <div>说明：</div>
    <div style="white-space: pre-wrap;">${this.temp.remark}</div>`
          this.$confirm(info,'优惠券一旦生成，不可修改，是否继续？', {
            dangerouslyUseHTMLString: true
          }).then(() => {
            let params = Object.assign({}, this.temp)
            couponSave(params).then(() => {
              this.dialogAddFormVisible = false
              this.getList()
              this.$message.success("操作成功");
            })
          })
        }
      })
    },
    handleDelete(row) {
      let params = { ids: row.id}
      this.$confirm('是否继续删除？').then(() => {
        couponRemove(params).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功！',
            type: 'success',
          })
          this.getList()
        })
      })
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
}
</script>

<style lang='scss' scoped>
  
</style>